<?php
class Agitum_Controller_Plugin_AccessCheck extends Zend_Controller_Plugin_Abstract
{
	private $_acl = null;

	public function preDispatch(Zend_Controller_Request_Abstract $request)
	{
//        printf( "Class: %s; Method: %s, File: %s; Line: %s<br/>\n", __CLASS__, __FUNCTION__, __FILE__, __LINE__);

		$auth = Zend_Auth::getInstance();
		$role = ($auth->hasIdentity()) ? (string)$auth->getIdentity()->role : 'guest';
		
		$controller = $request->getControllerName();
		$action = $request->getActionName();
		$module = $request->getModuleName();

	    $mvc = array('module'=>$module, 'controller'=>$controller, 'action'=>$action);
		$id = implode('_', array_values($mvc));
		$slot = new Agitum_Model_Cache_Slot_Page(md5($id));
		$page = $slot->load();
		if ( !$page ) 
		{
		    $db = Zend_Registry::get('Zend_Db');
		    $page = Agitum_Model_Page::findByMVC($mvc);
		    if ($page)
    		    $slot->addTag(new Agitum_Model_Cache_Tag_Page($page->id));
    		$slot->save($page);
		}
		
		if (!$page) return;
		
		$resource = $page->name;
		$privilege = $action;

        $acl = Zend_Registry::get('Zend_Acl');

		if( $acl->has($resource) && !$acl->isAllowed((string)$role, $resource, $privilege))
		{
			$request->setControllerName('error')
					->setModuleName('default')
					->setActionName('access');
			$this->_response->setHttpResponseCode(403);
		}
	}
}
